import React, { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { useHistory } from 'react-router-dom';
import seaImage from '../images/sea.png';
import tribalImage from '../images/Tribal.png';
import Professional from '../images/Professional.png';
import Bohemian from '../images/Bohemian.jpg';
import Minimalist from '../images/Minimalist.jpg';
import Industrial from '../images/Industrial.jpg';
import Cyberpunk from '../images/Cyberpunk.jpg';
import Scandinavian from '../images/Scandinavian.jpg';

const Design: React.FC = () => {
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const [selectedStyle, setSelectedStyle] = useState<string>('modern');
  const [selectedRoomType, setSelectedRoomType] = useState<string>('living-room');
  const [isProcessing, setIsProcessing] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const history = useHistory();

  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type
      if (!file.type.match('image.*')) {
        alert('Please select an image file');
        return;
      }

      // Validate file size (10MB limit)
      if (file.size > 10 * 1024 * 1024) {
        alert('File size should be less than 10MB');
        return;
      }

      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null); // Reset processed image when new image is uploaded
      };
      reader.readAsDataURL(file);
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    
    const file = event.dataTransfer.files[0];
    if (file) {
      if (!file.type.match('image.*')) {
        alert('Please drop an image file');
        return;
      }

      if (file.size > 10 * 1024 * 1024) {
        alert('File size should be less than 10MB');
        return;
      }

      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleGenerate = async () => {

       
    if (!selectedImage) return;
    
    // 检查用户是否有足够的积分  暂时注释 
    const currentCredits = parseInt(localStorage.getItem('credits') || '0');
    if (currentCredits < 1) {
      // alert('You do not have enough credits. Please purchase more credits to continue.');
      // history.push('/buy-credits');
      // return;
    }

    setIsProcessing(true);
    try {

      // 将 base64 图片数据转换为 Blob  没事我在调试
      // const base64Data = selectedImage.split(',')[1];
      // console.log(selectedImage);      
      // console.log(base64Data);      
      // const blob = await fetch(`data:image/jpeg;base64,${base64Data}`).then(res => res.blob());
      // 不需要转 直接用base64 
      // const blob = base64Data; 
      
      

      // 创建 FormData 对象
      // 直接复制下面代码  传递着4个参数google_id，model_id，img，content 就完事了 嗯 回调直接 使用data.data 作为图片的url 嗯
      // 嗯  model_id 如果是 分析的话 需要4
      //这是我的改就行来继续 看下谷歌登录看完 看完完事嗯
      const formData = new FormData(); 

      const google_id = localStorage.getItem('google_id');
      formData.append('google_id', google_id || '');
      formData.append('model_id', '5');
      formData.append('img', selectedImage );
  
      const content = `以${selectedStyle} 风格 设计 ${selectedRoomType}`;
      formData.append('content', content);
      
      // 发送请求到后端
      const response = await fetch('https://aa.jstang.cn/api/ai/call', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      // 回调直接 使用data.data 作为图片的url 
      const data = await response.json();
      console.log(data);
      setProcessedImage(data.data); 
      
      // 消费积分
      const newCredits = currentCredits - 1;
      localStorage.setItem('credits', newCredits.toString());
      
    } catch (error) {
      console.error('Error processing image:', error);
      alert('Failed to process image. Please try again.');
    } finally {
      setIsProcessing(false);
    }
  };

  const roomTypes = [
    { id: 'living-room', name: 'Living Room' },
    { id: 'bedroom', name: 'Bedroom' },
    { id: 'kitchen', name: 'Kitchen' },
    { id: 'bathroom', name: 'Bathroom' },
    { id: 'office', name: 'Office' },
    { id: 'dining-room', name: 'Dining Room' },
    { id: 'game-room', name: 'Game Room' },
    { id: 'basement', name: 'Basement' },
    { id: 'outdoor-terrace', name: 'Outdoor Terrace' },
  ];

  const designStyles = [
    { id: 'modern', name: 'Modern', image: 'https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80' },
    { id: 'minimalist', name: 'Minimalist', image: Minimalist },
    { id: 'scandinavian', name: 'Scandinavian', image: Scandinavian },
    { id: 'industrial', name: 'Industrial', image: Industrial },
    { id: 'bohemian', name: 'Bohemian', image: Bohemian },
    { id: 'tribal', name: 'Tribal', image: tribalImage },
    { id: 'cyberpunk', name: 'Cyberpunk', image: Cyberpunk },
    { id: 'coastal', name: 'Coastal', image: seaImage },
    { id: 'professional', name: 'Professional', image: Professional },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 py-12">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">Room Designer</h1>
          <p className="text-xl text-gray-600">Upload your room photo and let AI transform it into your dream space</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left Column - Upload, Room Type, and Style Selection */}
          <div className="space-y-8">
            {/* Image Upload Section */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5 }}
              className="bg-white rounded-xl shadow-lg p-6"
            >
              <div className="mb-6">
                <label className="block text-lg font-medium text-gray-700 mb-2">
                  Upload Your Room Photo
                </label>
                <div 
                  className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer"
                  onClick={() => fileInputRef.current?.click()}
                  onDragOver={handleDragOver}
                  onDrop={handleDrop}
                >
                  <div className="space-y-1 text-center">
                    {selectedImage ? (
                      <div className="relative">
                        <img
                          src={selectedImage}
                          alt="Uploaded room"
                          className="max-h-96 w-auto mx-auto rounded-lg"
                        />
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setSelectedImage(null);
                            setProcessedImage(null);
                          }}
                          className="absolute top-2 right-2 bg-red-500 text-white p-2 rounded-full hover:bg-red-600 transition-colors"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                          </svg>
                        </button>
                      </div>
                    ) : (
                      <>
                        <svg
                          className="mx-auto h-12 w-12 text-gray-400"
                          stroke="currentColor"
                          fill="none"
                          viewBox="0 0 48 48"
                        >
                          <path
                            d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                            strokeWidth={2}
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                        <div className="flex text-sm text-gray-600">
                          <span className="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500">
                            Upload a file
                          </span>
                          <p className="pl-1">or drag and drop</p>
                        </div>
                        <p className="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
                      </>
                    )}
                    {uploadProgress > 0 && uploadProgress < 100 && (
                      <div className="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                        <div
                          className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
                          style={{ width: `${uploadProgress}%` }}
                        ></div>
                      </div>
                    )}
                  </div>
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  className="hidden"
                  accept="image/*"
                  onChange={handleImageUpload}
                />
              </div>

              {/* Room Type Selection */}
              <div className="mt-8">
                <label className="block text-lg font-medium text-gray-700 mb-4">
                  Select Room Type
                </label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                  {roomTypes.map((room) => (
                    <button
                      key={room.id}
                      onClick={() => setSelectedRoomType(room.id)}
                      className={`py-2 px-4 rounded-lg text-sm font-medium transition-colors ${
                        selectedRoomType === room.id
                          ? 'bg-blue-500 text-white'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                      }`}
                    >
                      {room.name}
                    </button>
                  ))}
                </div>
              </div>
            </motion.div>
                  
            {/* Style Selection */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="bg-white rounded-xl shadow-lg p-6"
            >
              <label className="block text-lg font-medium text-gray-700 mb-4">
                Choose Design Style
              </label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {designStyles.map((style) => (
                  <button
                    key={style.id}
                    onClick={() => setSelectedStyle(style.id)}
                    className={`relative rounded-lg overflow-hidden group ${
                      selectedStyle === style.id ? 'ring-2 ring-blue-500' : ''
                    }`}
                  >
                    <img
                      src={style.image}
                      alt={style.name}
                      className="w-full h-32 object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center">
                      <span className="text-white font-medium">{style.name}</span>
                    </div>
                  </button>
                ))}
              </div>

              <div className="mt-6">
                
                {/* <button
                  onClick={handleGenerate}
                  disabled={!selectedImage || isProcessing}
                  className={`w-full py-3 px-4 rounded-lg text-white font-medium transition-colors ${
                    !selectedImage || isProcessing
                      ? 'bg-gray-400 cursor-not-allowed'
                      : 'bg-blue-500 hover:bg-blue-600'
                  }`}
                >
                  {isProcessing ? (
                    <div className="flex items-center justify-center">
                      <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      Processing...
                    </div>
                  ) : (
                    <>Generate Design <span className="ml-2 text-sm opacity-80">(Cost: 1 credit)</span></>
                  )}
                </button> */}
                {/* 这是临时测试*/}
                <button
                  onClick={handleGenerate}
                  
                  className={`w-full py-3 px-4 rounded-lg text-white font-medium transition-colors ${
                    !selectedImage || isProcessing
                      ? 'bg-gray-400'
                      : 'bg-blue-500 hover:bg-blue-600'
                  }`}
                >
                  {isProcessing ? (
                    <div className="flex items-center justify-center">
                      <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      Processing...
                    </div>
                  ) : (
                    <>Generate Design <span className="ml-2 text-sm opacity-80">(Cost: 1 credit)</span></>
                  )}
                </button>
              </div>
            </motion.div>
          </div>

          {/* Right Column - Preview or Before/After Comparison */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
            className="bg-white rounded-xl shadow-lg p-6"
          >
            {processedImage ? (
              <>
                <h3 className="text-lg font-medium text-gray-700 mb-4">Before & After</h3>
                <div className="space-y-8">
                  <div>
                    <p className="text-sm text-gray-500 mb-2">Original</p>
                    <div className="relative w-full h-[500px] rounded-lg overflow-hidden shadow-lg">
                      <img
                        src={selectedImage || ''}
                        alt="Original room"
                        className="w-full h-full object-contain bg-gray-100"
                      />
                    </div>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500 mb-2">Redesigned</p>
                    <div className="relative w-full h-[500px] rounded-lg overflow-hidden shadow-lg">
                      <img
                        src={processedImage}
                        alt="Redesigned room"
                        className="w-full h-full object-contain bg-gray-100"
                      />
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <div className="space-y-8">
                <div>
                  <p className="text-sm text-gray-500 mb-2">Preview</p>
                  <div className="relative w-full h-[500px] rounded-lg overflow-hidden shadow-lg">
                    <img
                      src="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80"
                      alt="Preview"
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                      <div className="text-center text-white">
                        <p className="text-2xl font-bold mb-2">Your Design Preview</p>
                        <p className="text-lg">Upload a room photo and select a style to see the magic!</p>
                      </div>
                    </div>
                  </div>
                </div>
                <div>
                  <p className="text-sm text-gray-500 mb-2">How it works</p>
                  <div className="relative w-full h-[500px] rounded-lg overflow-hidden shadow-lg">
                    <img
                      src={seaImage}
                      alt="How it works"
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                      <div className="text-center text-white">
                        <p className="text-2xl font-bold mb-2">Step by Step</p>
                        <ol className="text-left text-lg space-y-2">
                          <li>1. Upload your room photo</li>
                          <li>2. Select room type</li>
                          <li>3. Choose design style</li>
                          <li>4. Click Generate Design</li>
                        </ol>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </motion.div>
        </div>
      </div>
    </div>
  );
};

export default Design; 
